import ProductCompanyAPI from '@/api/ProductCompany';
import {
  Box,
  FieldCols,
  FieldEffect,
  FormSection,
  useCall,
  useForceUpdate,
  useQueryValues,
  useReq,
} from '@/components';
import { JSONParseFallback, pathJoin } from '@/utils';
import { catchAndScrollFor } from '@/utils/fp';
import { Button, Form, message, Space, Spin } from 'antd';
import React, { useEffect, useMemo, useRef } from 'react';
import { dataToForm, fields, formToData, numId } from './components/shared';

function CompanyEditPage(props) {
  const forceUpdate = useForceUpdate();
  const data = sessionStorage.getItem('EditCompanyInfo');
  const [action] = useQueryValues('action');
  const originDataRef = useRef(null);
  const [form] = Form.useForm();
  const saveXhr = useReq(ProductCompanyAPI.insertOrUpdate);
  const queryXhr = useReq(ProductCompanyAPI.getList);

  const setOriginData = (originData) => {
    if (!originData) return;
    originDataRef.current = originData;
    form.setFieldsValue(dataToForm(originData));
    forceUpdate();
  };

  useEffect(() => {
    // 回显
    if (data && action === 'edit') {
      setOriginData(JSONParseFallback(data));
    }
  }, []);
  const onSave = useCall(async () => {
    const formData = await form.validateFields().catch(catchAndScrollFor(form));
    const data = formToData(formData, originDataRef.current);
    await saveXhr.start(data);
    message.success('保存成功');
    props.history?.replace(pathJoin(props?.location.pathname, '../'));
  });

  const claimAddrId = useMemo(numId, []);

  return (
    <Spin spinning={[saveXhr.status, queryXhr.status].includes('loading')}>
      <Form form={form}>
        <FieldEffect name='id' />
        <FieldEffect
          name={['companyClaimSettlementAddressList', 0, 'addressClaimSettlementAddressId']}
          initialValue={claimAddrId}
        />

        <FormSection title='基础信息'>
          <FieldCols form={form} fields={fields.base} />
        </FormSection>

        <FormSection title='携赔'>
          <FieldCols form={form} fields={fields.xp} />
        </FormSection>

        <FormSection title='点滴保'>
          <FieldCols form={form} fields={fields.dd} />
        </FormSection>

        <FormSection title='运营服务'>
          <FieldCols form={form} fields={fields.service} />
        </FormSection>

        <FormSection title='相关附件'>
          <FieldCols form={form} fields={fields.attachment} />
        </FormSection>
      </Form>

      <Box flex jus='center' py={3} className='form-page-btn'>
        <Space size='large'>
          <Button onClick={props.history?.goBack}>返回</Button>
          <Button type='primary' onClick={onSave}>
            保存
          </Button>
        </Space>
      </Box>
    </Spin>
  );
}

export default CompanyEditPage;
